package com.mfc.education.service.email.service.impl;

import com.mfc.education.common.base.result.ResultCodeEnum;
import com.mfc.education.service.base.exception.EduException;
import com.mfc.education.service.email.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * @author mfc
 * @since 2021/9/24
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {


    @Autowired
    JavaMailSenderImpl mailSender;

    @Value("${spring.mail.username}")
    private String username;

    @Async
    @Override
    public void send(String qqEmail, String checkCode) {

        log.info("开始");
        //邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            mimeMessageHelper.setSubject("【在线教育平台】注册账号");
            mimeMessageHelper.setText(
                    "有人要求您在 <a href='https://www.baidu.com/'><b style='color:#006699'>在线教育平台</b></a> 上注册账号。 <br> <br>" +
                    "如果不是您，您可以直接忽略此电子邮件。<br> <br> 邮箱验证码：<b style='color:#006699'>"+checkCode+"</b>", true);
            mimeMessageHelper.setTo(qqEmail);
            mimeMessageHelper.setFrom(username);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("邮箱发送失败 " + " - code: " + checkCode + ", message: " + e.getMessage());
            throw new EduException(ResultCodeEnum.EMAIL_SEND_ERROR);
        }
        log.info("结束");
    }
}
